package com.changgou.service.impl;

import com.changgou.dao.BrandMapper;
import com.changgou.goods.pojo.Brand;
import com.changgou.service.BrandService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 品牌信息业务逻辑实现
 *
 * @author gaofeng
 * @date 2025年04月18日 13:56
 */
@Service("brandServiceImpl")
public class BrandServiceImpl implements BrandService {
    @Resource
    private BrandMapper brandMapper;

    @Override
    public List<Brand> selectAllBrands() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand selectBrandById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public void insert(Brand brand) {
        brandMapper.insertSelective(brand);
    }

    @Override
    public void update(Brand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void delete(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Brand> findList(Brand brand) {
        Example example = buildExample(brand);
        return brandMapper.selectByExample(example);
    }

    @Override
    public PageInfo<Brand> findPage(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(brandMapper.selectAll());
    }

    @Override
    public PageInfo<Brand> findPage(Integer page, Integer size, Brand brand) {
        PageHelper.startPage(page, size);
        Example example = buildExample(brand);
        return new PageInfo<>(brandMapper.selectByExample(example));
    }

    @Override
    public List<Brand> findByCategoryId(Integer categoryId) {
        return brandMapper.findByCategoryId(categoryId);
    }

    private Example buildExample(Brand brand) {
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if (brand != null) {
            if (StringUtils.isNotBlank(brand.getName())) {
                criteria.andLike("name", "%" + brand.getName() + "%");
            }

            if (StringUtils.isNotBlank(brand.getLetter())) {
                criteria.andEqualTo("letter", brand.getLetter());
            }
        }

        return example;
    }
}
